package com.itg.vms.filter;

import com.alibaba.fastjson.JSONObject;
import com.itg.vms.entity.User;
import com.itg.vms.util.AjaxResult;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录过滤器
 *
 * @author zjzaki
 * @create 2023年03月06日 13:36:37
 */
@WebFilter(urlPatterns = {"/apiv2/*"})
public class APIv2 implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        System.out.println("进入过滤器了");
        //转换成HttpServletRequest
        HttpServletRequest req = (HttpServletRequest) request;
        //转换成HttpServletRequest
        HttpServletResponse resp = (HttpServletResponse) response;
        //得到存在session中的登录用户
        User user = (User) req.getSession().getAttribute("loginUser");
        //判断是否登录
        if (user == null) {
            System.out.println("被过滤器拦截了");
            resp.getWriter().write(JSONObject.toJSONString(AjaxResult.error(302,"用户未登录")));
        //判断是否有管理员权限
        }else if("0".equals(user.getUserType())){
            System.out.println("权限没了----->"+user);
            // 没有管理权限
            resp.getWriter().write(JSONObject.toJSONString(AjaxResult.error(403,"权限呢？？，还想进管理页面")));
        } else{
            System.out.println(user);
            //放行
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
